// Physical memory allocator, for user processes,
// kernel stacks, page-table pages,
// and pipe buffers. Allocates whole 4096-byte pages.

#include "types.h"
#include "param.h"
#include "memlayout.h"
#include "spinlock.h"
#include "riscv.h"
#include "defs.h"

void freerange(void *pa_start, void *pa_end);

extern char end[]; // first address after kernel.
                   // defined by kernel.ld.

struct run {
  struct run *next;
};

struct {
  struct spinlock lock;
  struct run *freelist;

  // for each physical page, a "reference count" of the number of user page tables that refer to that page
  #define REFCOUNT_SIZE (PHYSTOP-KERNBASE)/PGSIZE
  int refcount[REFCOUNT_SIZE];
  #define PGNUM(pa) (((uint64)pa-KERNBASE)/PGSIZE)
} kmem;


void
kinit()
{
  memset(kmem.refcount, 0, sizeof(kmem.refcount));

  initlock(&kmem.lock, "kmem");
  freerange(end, (void*)PHYSTOP);
}

// initializing the allocator; see kinit above.
void
_kfree(void *pa)
{
  struct run *r;
  // Fill with junk to catch dangling refs.
  memset(pa, 1, PGSIZE);

  r = (struct run*)pa;

  acquire(&kmem.lock);
  r->next = kmem.freelist;
  kmem.freelist = r;
  release(&kmem.lock);
}

void
freerange(void *pa_start, void *pa_end)
{
  char *p;
  p = (char*)PGROUNDUP((uint64)pa_start);
  for(; p + PGSIZE <= (char*)pa_end; p += PGSIZE)
    _kfree(p);
}


// Free the page of physical memory pointed at by pa,
// which normally should have been returned by a
// call to kalloc().  (The exception is when
// initializing the allocator; see kinit above.)
void
kfree(void *pa)
{
  struct run *r;

  if(((uint64)pa % PGSIZE) != 0 || (char*)pa < end || (uint64)pa >= PHYSTOP)
    panic("kfree");

  int rnum = __sync_sub_and_fetch(&kmem.refcount[PGNUM(pa)], 1);
  __sync_synchronize();
    if (rnum==0) {  
    // Fill with junk to catch dangling refs.
    memset(pa, 1, PGSIZE);

    r = (struct run*)pa;

    acquire(&kmem.lock);
    r->next = kmem.freelist;
    kmem.freelist = r;
    release(&kmem.lock);
  }else if (rnum<0) {
    panic("kfree: double free");
  }  
}

void *
kmap(uint64 pa)
{
  if(((uint64)pa % PGSIZE) != 0 || (char*)pa < end || (uint64)pa >= PHYSTOP)
    panic("kref");
  if (__sync_fetch_and_add(&kmem.refcount[PGNUM(pa)], 1)==0)  {
    panic("kref: refcount==0");
  }
  return (void*)pa;  
}

int
krefcount(uint64 pa){
  return kmem.refcount[PGNUM(pa)];
}

// Allocate one 4096-byte page of physical memory.
// Returns a pointer that the kernel can use.
// Returns 0 if the memory cannot be allocated.
void *
kalloc(void)
{
  struct run *r;

  acquire(&kmem.lock);
  r = kmem.freelist;
  if(r)
    kmem.freelist = r->next;
  release(&kmem.lock);

  if(r){
    if (kmem.refcount[PGNUM(r)]) {
      panic("kalloc: double alloc");
    }    
    kmem.refcount[PGNUM(r)]++;
    memset((char*)r, 5, PGSIZE); // fill with junk
  }
  return (void*)r;
}
